﻿using System.Collections.Concurrent;
using System.Net.NetworkInformation;
using System.Threading.Tasks;

namespace BookSourceVerification.pool;

public class PingPool
{
    private readonly BlockingCollection<Ping> _pings;

    public PingPool(int max)
    {
        this._pings = new BlockingCollection<Ping>(max);
        for (int i = 0; i < max; i++)
        {
            this._pings.Add(new Ping());
        }
    }

    public void Release(Ping ping)
    {
        this._pings.Add(ping);
    }

    public Ping Acquire()
    {
        return this._pings.Take();
    }

    public static async Task Test01()
    {
        string url = "https://www.baidu.com";
        var pingPool = new PingPool(10);
        Ping? ping = null;
        try
        {
            ping = pingPool.Acquire();
            var reply = await ping.SendPingAsync(url);
        }
        finally
        {
            if (ping is not null)
            {
                pingPool.Release(ping);
            }
        }

        pingPool.ShutDown();
    }

    public void ShutDown()
    {
        foreach (var ping in this._pings)
        {
            ping.Dispose();
        }
    }
}